using System;
using System.Windows;
using System.Windows.Controls;

using EMan.Common.DependencyInjection;
using EMan.GUI.Common.EntityEditing;
using EMan.Interface.Common;

using TrueCode.Core.Aspects;

namespace EMan.GUI.Common
{
  public class BaseViewUserControl : UserControl, IView 
  {
    private readonly IFactory _factory;

    protected BaseViewUserControl( [NotNull] IFactory factory )
    {
      if( factory == null ) throw new ArgumentNullException( "factory" );
      _factory = factory;
    }

    public IFactory Factory
    {
      get { return _factory; }
    }

    public object UiElement
    {
      get { return this; }
    }

    public void ShowEditor( [NotNull] Type editorViewType, [NotNull] object editSession )
    {
      if( editorViewType == null ) throw new ArgumentNullException( "editorViewType" );
      if( editSession == null ) throw new ArgumentNullException( "editSession" );

      var view = (IEntityEditorGuiElement)Factory.Resolve( editorViewType, editSession );
      ShowEditor( view );
    }

    public bool ShowEditor( IEntityEditorGuiElement guiElement )
    {
      var dlg = new EntityEditorViewHost( guiElement );
      dlg.ShowDialog();
      return guiElement.Submitted;
    }

    void IView.ShowMessage( string message, MessageType messageType )
    {
      MessageBox.Show( this.GetTopParent(), message, "", MessageBoxButton.OK, messageType.ToWpf() );
    }

    Answer IView.AskConfirmaiton( string message, MessageType messageType, PossibleAnswers possibleAnswers )
    {
      return MessageBox.Show( this.GetTopParent(), message, "", possibleAnswers.ToWpf(), messageType.ToWpf() ).ToCommon();
    }

    private void CallActionOnCorrectThread( Action action )
    {
      if( Dispatcher.CheckAccess() )
        action();
      else
        Dispatcher.Invoke( action );
    }

    [Obsolete("Do not use this contstructor, it is for WPF designer only")]
    protected BaseViewUserControl(){}
  }
}